package com.fan.demo;

import org.apache.shardingsphere.api.config.sharding.ShardingRuleConfiguration;
import org.apache.shardingsphere.api.config.sharding.TableRuleConfiguration;
import org.apache.shardingsphere.api.config.sharding.strategy.StandardShardingStrategyConfiguration;
import org.apache.shardingsphere.shardingjdbc.api.ShardingDataSourceFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @Description:
 * @Author: Fan
 * @Date: 2021/12/2 21:51
 * @Version 1.0
 **/
//@Configuration
//@EnableConfigurationProperties(ShardingSphereConfigProperties.class)
public class ShardingSphereConfiguration {

//    @Autowired
    ShardingSphereConfigProperties properties;

//    @Bean
    DataSource shardingDataSource() throws SQLException {
        // 数据分片规则配置
        ShardingRuleConfiguration shardingRuleConfig = new ShardingRuleConfiguration();
        // 实际参与分片的表
        shardingRuleConfig.getTableRuleConfigs().add(getOrderTableRuleConfiguration());
        // 虚拟表（总表）
        shardingRuleConfig.getBindingTableGroups().add("cert_event");
        // 默认分表策略
        shardingRuleConfig.setDefaultTableShardingStrategyConfig(new StandardShardingStrategyConfiguration("createTime", null));
        // 配置项
        Properties shardingProps = new Properties();
        shardingProps.put("sql.show", true);
        shardingProps.put("sql.simple", true);

        return ShardingDataSourceFactory.createDataSource(createDataSourceMap(), shardingRuleConfig, shardingProps);
    }

    TableRuleConfiguration getOrderTableRuleConfiguration() {
        TableRuleConfiguration result = new TableRuleConfiguration("t_order", "master.event_cert," +
                "master.event_cert_$->{2021..2022}0$->{1..4}");
        return result;
    }

    /**
     * 构造数据源
     *
     * @return
     */
    Map<String, DataSource> createDataSourceMap() {
        Map<String, DataSource> result = new HashMap<>();
        result.put("master", DataSourceUtil.createDataSource("test-shardingsphere"));
        return result;
    }
}
